package be.djdb.game;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.*;
import javax.swing.plaf.SliderUI;

import be.djdb.Statics;
import be.djdb.game.essetials.Direction;
import be.djdb.game.essetials.Level0;
import be.djdb.game.essetials.MyLevel;
import be.djdb.game.essetials.MyPlayer;
import be.djdb.game.players.Hunter;
import be.djdb.game.players.Hunterskin;
import be.djdb.game.players.Opponent;
import be.djdb.game.players.OpponentSkin;




/**
 * @author user
 *
 */
public class Playground extends JPanel implements ActionListener,Runnable{
	private static final long serialVersionUID = 8187222665384962970L;
	private MyLevel level;
	private boolean isingame = false;
	private MyPlayer dief;
	private int Ghosts = 6;//ghost pieces
	private int maxghosts;
	private Timer timer;
	Playground() {
		dief = new Hunter(3,new Hunterskin());//score and lifes
		dief.setSpeed(1);
		level =new Level0(dief);
		maxghosts = Ghosts;
		addKeyListener(new Keylistener(Direction.FIXED));
        setFocusable(true);
        setBackground(Color.black);
        setDoubleBuffered(true);
        Opponent[] ghosts = new Opponent[maxghosts];
        for (int i = 0; i < maxghosts; i++) {
			ghosts[i]=new Opponent(1,new OpponentSkin());
		}
        this.level.setopponent(ghosts);
        setFocusable(true);
	}
    public void paint(Graphics g){
    	super.paint(g);
        if (isingame){
        	if(Statics.FOLLOW){	log(Level.ALL,"toGo");}
            paint_Go(g);
        }else{
        	System.out.println("toInit"); 
            paint_start(g);
        }
    }
	private void paint_start(Graphics g){
		Graphics2D g2d = (Graphics2D) g;
		level.paint(g2d);
        g2d.setColor(new Color(0, 32, 48));
        int x = 50;
        int y = level.Ysize / 2 - 30;
		int height = 50;
		int width= level.Xsize - 100;
		g2d.fillRect(x, y, width, height);
        g2d.setColor(Color.white);
        g2d.drawRect(x, y, width, height);
        String s = "UNDER CONSTRUCTION, please kill the process by 'ctrl+alt+del'if it stop working /n";
        String s2 = "Press 's' to start.";
        Font small = new Font("Arial", Font.BOLD, 14);
        FontMetrics metr = this.getFontMetrics(small);
        g2d.setColor(Color.white);
        g2d.setFont(small);
        g2d.drawString(s, (level.Xsize - metr.stringWidth(s)) / 2, level.Ysize / 2 -height);
        g2d.drawString(s2, (level.Xsize - metr.stringWidth(s2)) / 2, level.Ysize / 2);
	}
	private void paint_Go(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;
		level.paint(g2d);
		if(Statics.FOLLOW){	log(Level.FINE,"Pacman Paint");}
		dief.animate();
		if(dief.getface() !=null)
			g2d.drawImage(dief.getface(), dief.getpos().x() - 1, dief.getpos().y() + 1, this);
		else
			if(Statics.DEBUG){	System.out.println("no image found");}
		if(level.CanMoveto(dief.getpos(),dief.getdirection())) {
			dief.move();
		}else{
			if(Statics.FOLLOW){	log(Level.INFO,"can not move");}
		}
		for (int i = 0; i < level.opponents.length; i++){
			Opponent o=level.MoveOpponent(i);
			g.drawImage(o.getface(),o.getpos().x() - 1,o.getpos().y() + 1, this);
		}

	}
	public void actionPerformed(ActionEvent e){
		if(Statics.FOLLOW){	log(Level.INFO,"TIMER INTERVAL(actionPerformed)");}
		repaint();
	}
	public void addNotify(){    
	        super.addNotify();
	}
	public void initializeGAME() {
		log(Level.ALL,"initializeGAME");
		System.out.println("setstart");
		//level.LevelInit();
	}
	public void Startgame(int fps){
		if (!isingame){
			isingame = true;
			initializeGAME();
	        /**
	         *een Timer en initialiseert zowel de initiële vertraging en tussen-event vertraging van milliseconden vertraging. 
	         *Indien vertraging  kleiner is of gelijk is aan nul dan, de timer branden zodra deze is gestart. 
	         *Als listener niet nul is, het is geregistreerd als een actionlistener op de timer.
	         */
			timer = new Timer(100,this);
	        //timer();
			timer.start();
		}
	}
	public boolean isGamestarted() {
		return this.isingame;
	}
	public void IwanttoSTOP() {
		if (timer.isRunning()){
			isingame=false;
		}
	}
	public void IwanttoPAUZE() {
		  if (timer.isRunning())
              timer.stop();
          else timer.start();
	}
    public void Death() {
        dief.die();
        if (dief.haslives())
        	isingame = false;
    }
    public class Keylistener extends KeyAdapter {
		private Direction actualdir ;
		public Keylistener(Direction dir) {
			actualdir = dir;
		}
		public void keyPressed(KeyEvent e) {
          int key = e.getKeyCode();
          if(level ==null){
        	  if(Statics.FOLLOW){System.out.print("NULL ");}
          }
          if (isGamestarted()){
        	  if(Statics.FOLLOW){System.out.print("change to ");}
        	  if(level.CanChangeDirection(
        			  level.player.getpos(),
        			  actualdir)){
        		  if (key == KeyEvent.VK_LEFT){
        			actualdir = Direction.LEFT;
        			level.player.setDirection(actualdir);
                  }else if (key == KeyEvent.VK_RIGHT) {
                	  actualdir = Direction.RIGHT;
                	  level.player.setDirection(actualdir);
                  }else if (key == KeyEvent.VK_UP){
                	  actualdir = Direction.UP;
                	  level.player.setDirection(actualdir);
                  }else if (key == KeyEvent.VK_DOWN){
                	  actualdir = Direction.DOWN;
                	  level.player.setDirection(actualdir);
                  }
        	  }else if (key == KeyEvent.VK_ESCAPE){
        		  IwanttoSTOP();
        	  }else if (key == KeyEvent.VK_PAUSE) {
        		  IwanttoPAUZE();
        	  }else{
        		  if(Statics.FOLLOW){System.out.print("can't change direction on playground");}
        		  
        		  level.toString();
        	  }
          }else{
            if (key == 's' || key == 'S'){
            	if(Statics.FOLLOW){	log(Level.ALL,"Push 's' or 'S' ");
            		Startgame(10000);
            	}else{
            		Startgame(1);
            	}
            	
            }
          }
		}
    }
	private static  void log(Level level,String msg ){
	    String tag ="<>>>>*"+Statics.LIBNAME+"-"+Statics.COPYRIGHTBY+"*<<<<>";
	    Logger.getLogger(Playground.class.getName()).log(level, tag + msg);
	}
	@Override
	protected void finalize() throws Throwable {
		timer.stop();
		timer=null;
		super.finalize();
	}
	@Override
	public String toString() {		
		return super.toString();
	}
	@Override
	public void run() {
		//sleep(200);
		
	}
}
